using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using FactoryPattern.Domain;

namespace FactoryPattern.Factories
{
    public sealed class SuitFactoryReflected
    {
        #region implemented

        Dictionary<SuitType, Type> _registered = new Dictionary<SuitType, Type>();
        Dictionary<SuitType, Suit> _loaded = new Dictionary<SuitType, Suit>();

        public SuitFactoryReflected()
        {
            Register(SuitType.Armani, typeof(Armani));
            Register(SuitType.GolfSuit, typeof(GolfSuit));
            Register(SuitType.MotorcycleSuit, typeof(MotorcycleSuit));
        }
        public Suit CreateSuit(SuitType suitType)
        {
            if (!_loaded.ContainsKey(suitType))
                Load(suitType);

            return _loaded.ContainsKey(suitType) ? _loaded[suitType] : null;
        }

        private void Load(SuitType suitType)
        {
            if(_registered.ContainsKey(suitType) && !_loaded.ContainsKey(suitType))
            {
                _loaded.Add(suitType, (Suit)Activator.CreateInstance(_registered[suitType]));
            }
            //foreach (KeyValuePair<SuitType, Type> obj in _registered)
            //{
            //    Type type = obj.Value;

            //    if (obj.Key == suitType && !_loaded.ContainsKey(obj.Key))
            //    {
            //        _loaded.Add(obj.Key, (Suit)Activator.CreateInstance(type));
            //    }
            //}
        }

        public void Register(SuitType suitType, Type type)
        {
            _registered.Add(suitType, type);
        }

        public Suit GetSuit(SuitType suitType)
        {
            Suit suit = null;
            foreach (KeyValuePair<SuitType, Suit> obj in _loaded)
            {
                if (_loaded.ContainsKey(suitType))
                {
                    suit = _loaded[suitType];
                    break;
                }
            }

            return suit;
        }

        #endregion

    }
}